package top.hundreds.oasys.service;

import org.springframework.stereotype.Service;
import top.hundreds.common.crud.service.BaseService;
import top.hundreds.oasys.bean.converter.Converter;
import top.hundreds.oasys.bean.entity.Menu;
import top.hundreds.oasys.bean.entity.Role;
import top.hundreds.oasys.bean.entity.RoleMenu;
import top.hundreds.oasys.bean.enums.MenuStatus;
import top.hundreds.oasys.bean.enums.RoleStatus;
import top.hundreds.oasys.bean.vo.MenuVo;
import top.hundreds.oasys.bean.vo.RoleVo;
import top.hundreds.oasys.mapper.MenuMapper;
import top.hundreds.oasys.mapper.RoleMapper;
import top.hundreds.oasys.mapper.RoleMenuMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * (Role)表服务实现类
 *
 * @author lcf
 * @since 2021-01-27 14:59:56
 */
@Service("roleService")
public class RoleService extends BaseService<Role, RoleMapper> {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private MenuMapper menuMapper;

    @Resource
    private Converter<Menu,MenuVo> menuVoBuilder;

    @Resource
    private Converter<Role, RoleVo> roleVoBuilder;

    public List<RoleVo> buildVoList(List<Role> roleList) {
        List<RoleVo> roleVoList = new ArrayList<>(roleList.size());
        for (Role role : roleList) {
            roleVoList.add(buildVo(role));
        }
        return roleVoList;
    }

    public RoleVo buildVo(Role role) {
        RoleVo roleVo = new RoleVo();
        roleVoBuilder.buildVo(role,roleVo);
        List<RoleMenu> roleMenus = roleMenuMapper.getByRoleId(role.getId());
        ArrayList<MenuVo> menuList = new ArrayList<>(roleMenus.size());
        for (RoleMenu roleMenu : roleMenus) {
            MenuVo menuVo = new MenuVo();
            Menu menu = menuMapper.selectById(roleMenu.getMenuId());
            menuVoBuilder.buildVo(menu,menuVo);
            menuVo.setStatusName(MenuStatus.formValue(menuVo.getStatus()).getLabel());
            menuList.add(menuVo);
        }
        roleVo.setMenuList(menuList);
        roleVo.setStatusName(RoleStatus.formValue(roleVo.getStatus()).getLabel());
        return roleVo;
    }


    public void changeMenu(Long roleId,List<Integer> menuIds) {
        roleMenuMapper.deleteByRoleId(roleId);
        for (Integer menuId : menuIds) {
            roleMenuMapper.insert(RoleMenu.builder().menuId((long)menuId).roleId(roleId).build());
        }
    }
}
